package de.slothsoft.wasbinich.core.database.webservice;

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import de.slothsoft.wasbinich.core.database.Database;
import de.slothsoft.wasbinich.core.database.DatabaseException;

public class AbstractWebserviceBean {

    protected static final String PARAMETER_DATA = "data"; //$NON-NLS-1$
    protected static final String PARAMETER_ACCESS_TOKEN = "access_token"; //$NON-NLS-1$

    protected static final Gson GSON = new GsonBuilder()
	    .registerTypeAdapter(String[].class, new StringArrayTypeAdapter()).enableComplexMapKeySerialization()
	    .create();

    private final RestCommunicator communicator;
    private boolean sendAccessToken;

    public AbstractWebserviceBean(RestCommunicator communicator) {
	this.communicator = communicator;
    }

    protected String get(String url) throws DatabaseException {
	if (this.sendAccessToken) {
	    System.err.println("Doing POST request instead of GET, because access token has to be send!"); //$NON-NLS-1$
	    return post(url);
	}
	return this.communicator.get(url);
    }

    protected String post(String url) throws DatabaseException {
	return post(url, new HashMap<String, String>());
    }

    protected String post(String url, String parameter) throws DatabaseException {
	Map<String, String> parameters = new HashMap<String, String>();
	parameters.put(PARAMETER_DATA, parameter);
	return post(url, parameters);
    }

    protected String post(String url, Map<String, String> parameters) throws DatabaseException {
	if (this.sendAccessToken) {
	    parameters.put(PARAMETER_ACCESS_TOKEN, getLoginToken());
	}
	return this.communicator.post(url, parameters);
    }

    protected String getLoginToken() throws DatabaseException {
	return Database.getInstance().getLoginBean().getLoginToken();
    }

    public boolean isSendAccessToken() {
	return this.sendAccessToken;
    }

    public void setSendAccessToken(boolean sendAccessToken) {
	this.sendAccessToken = sendAccessToken;
    }

}
